package com.lg.atp.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.BindException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.alibaba.fastjson.JSONObject;
import com.lg.atp.utils.DeviceConstants;
import com.lg.atp.utils.JobParameter;
import com.lg.atp.vo.device.MacacaDeviceInfo;

public class WSClient {

    public WSClient() {
    }

    public WSClient(String endpointUrl) {
        this.endpointUrl = endpointUrl;
    }

    private String endpointUrl = "http://192.168.149.128:3333";

    /**
     * 获取所有slave节点上的设备
     *
     */

     public List<MacacaDeviceInfo> getDeviceInfos() throws Exception {
        String url = endpointUrl+"/api/matc/devices/devices";
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream(),"utf-8"));//防止乱码
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            List<MacacaDeviceInfo> returnList = JSONObject.parseArray(json.toString(), MacacaDeviceInfo.class);
            return returnList;
        }catch (Exception e) {
			
		}
       return null;
    }

    /**
     * 根据设备id、控制类（run,stop,delete,record）,控制设备(reliable)
     *
     */
    public String controlDevicesById(String deviceId, String control) throws Exception {
        //String url = "http://192.168.164.129:3333/api/matc/devices/control_devices/5a6fd94eb72c201fc9615ef0/run";
        String url = endpointUrl+"/api/matc/devices/control_devices/" + deviceId + "/" + control;

        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream(),"utf-8"));//防止乱码
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            JSONObject data =JSONObject.parseObject(json.toString());
            if ("run".equals(control)) {
                String webSocketPort = data.getJSONObject("data").getString("webSocketPort");;
                return webSocketPort;
            }if ("record".equals(control)) {
                String webSocketPort = data.getJSONObject("data").getString("webSocketPort");;
                String webSourcePort = data.getJSONObject("data").getString("sourcePort");
                return webSocketPort+":"+webSourcePort;
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return "";

    }

    /**
     * 刷新所有slave节点上的设备
     *
     */
    /*

    public String deviceRefresh() throws Exception {
        String url = "http://" + endpointUrl + "/api/matc/devices/devices_refresh";
        WebClient client3 = WebClient.create(url);
        //
        Response res = client3.accept(MediaType.TEXT_PLAIN).type(MediaType.TEXT_PLAIN).get();
        if (res.getStatus() == 200) {
            return IOUtils.toString((InputStream) res.getEntity());
        }
        return "";

		*//*
		 * HttpClient httpClient = new HttpClient(); HttpMethod method = new
		 * PostMethod(url);
		 *
		 * httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(7000);
		 * httpClient.getHttpConnectionManager().getParams().setSoTimeout(7000);
		 *
		 * int executeMethod = httpClient.executeMethod(method);
		 *
		 * return String.valueOf(executeMethod);
		 *//*
    }

    *//**
     * 根据设备唯一标识、控制类型，控制设备
     *
     * @param String
     *            设备唯一标识
     * @param String
     *            控制类型
     * @return String
     * @throws Exception
     *//*
    public String controlDeviceById(String hpDeviceId, String control) throws Exception {
        String url = "http://" + endpointUrl + "/api/devices/" + hpDeviceId + "/" + control;

        WebClient client = WebClient.create(url);
        Response res = client.accept(MediaType.TEXT_PLAIN).type(MediaType.TEXT_PLAIN).post(null);
        if (res.getStatus() != 200) {
            return IOUtils.toString((InputStream) res.getEntity());
        }

        return "";
    }

    *//**
     * 获取设备信息json,并将其转化为HpDeviceInfo对象的集合
     *
     * @return List<HpDeviceInfo>
     * @throws Exception
     *//*
    public List<HpDeviceInfo> getDeviceInfo() throws Exception {

        String url = "http://" + endpointUrl + "/api/devices";
        WebClient client = WebClient.create(url);
        Response res = client.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).get();
        MappingJsonFactory factory = new MappingJsonFactory();
        JsonParser parser = factory.createJsonParser((InputStream) res.getEntity());
        List<HpDeviceInfo> returnList = parser.readValueAs(new TypeReference<List<HpDeviceInfo>>() {
        });
        return returnList;
    }

    *//**
     * 删除设备
     *
     * @return String
     * @throws Exception
     *//*
    public String deleteDeviceById(String id) throws Exception {
        String url = "http://" + endpointUrl + "/api/admin/devices/" + id + "/delete";
        WebClient client = WebClient.create(url);
        Response res = client.accept(MediaType.TEXT_PLAIN).type(MediaType.TEXT_PLAIN).post(null);
        if (res.getStatus() != 200) {
            return IOUtils.toString((InputStream) res.getEntity());
        }
        return "";
    }

    *//**
     * 根据设备端口截图
     *
     * @return String 图片的字节码
     * @throws Exception
     *//*
    public String screenShotByPortId(Integer portId) throws Exception {
        String url = "http://" + endpointUrl + ":" + portId + "/screenshot";
        WebClient client = WebClient.create(url);
        Response res = client.accept(MediaType.TEXT_PLAIN).type(MediaType.TEXT_PLAIN).get();
        return IOUtils.toString((InputStream) res.getEntity());
    }

    *//**
     * 刷新设备
     *
     * @return String 刷新结果（200：成功，500：失败）
     * @throws Exception
     *//*
    public String devicesRefresh() throws Exception {
        String url = "http://" + endpointUrl + "/api/admin/devices_refresh";
        // WebClient client = WebClient.create(url);
        //
        // Response res = client.accept(MediaType.TEXT_PLAIN)
        // .type(MediaType.TEXT_PLAIN).post(null);
        // if (res.getStatus() == 200) {
        // return IOUtils.toString((InputStream) res.getEntity());
        // }
        // return "";

        HttpClient httpClient = new HttpClient();
        HttpMethod method = new PostMethod(url);

        httpClient.getHttpConnectionManager().getParams().setSoTimeout(7000);

        int executeMethod = httpClient.executeMethod(method);

        return String.valueOf(executeMethod);

    }*/
    
    public String submitJob(JobParameter jobParameter) throws Exception{
		Integer deviceType = jobParameter.getDeviceType();

		if (deviceType == null) {
			throw new BindException("请指定创建job的设备类型是安卓实体机设备/安卓模拟器/ios实体机");
		}

		Integer appType = jobParameter.getAppType();

		if (appType == null) {
			throw new BindException("请指定要测试的应用类型，1native原生应用/ 2hybrid/3web");
		}

		StringBuilder url = new StringBuilder(endpointUrl);
		url.append("/");

		// 拼接url，1安卓实体机，2安卓模拟器, 3ios实体机
		/*
		 * if (DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_REAL.equals(deviceType))
		 * { url.append(DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_REAL_TEXT_JOB);
		 * } else if (DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_EMULATOR
		 * .equals(deviceType)) {
		 * url.append(DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_EMULATOR_TEXT_JOB
		 * ); } else if (DeviceConstants.AUTO_DEVICE_TYPE_IOS_EMULATOR
		 * .equals(deviceType)) {
		 * url.append(DeviceConstants.AUTO_DEVICE_TYPE_IOS_REAL_TEXT_JOB); }
		 * else { throw new BusinessException("传递的应用类型不合法，不支持该种类型"); }
		 */

		// 组装script_url
		NameValuePair scriptUrl = new NameValuePair(DeviceConstants.JOB_PARAMETER_SCRIPT_URL,
				jobParameter.getScriptUrl());

		// 组装app_url
		NameValuePair appUrl = new NameValuePair(DeviceConstants.JOB_PARAMETER_APP_URL, jobParameter.getAppUrl());

		// 组装result_url
		NameValuePair resultUrl = new NameValuePair(DeviceConstants.JOB_PARAMETER_RESULT_URL,
				jobParameter.getResultUrl());

		// 组装app_type
		NameValuePair appTypeValuePair = new NameValuePair();
		appTypeValuePair.setName(DeviceConstants.AUTO_DEVICE_APP_TYPE);

		if (DeviceConstants.AUTO_DEVICE_APP_TYPE_NATIVE.equals(appType)) {
			appTypeValuePair.setValue(DeviceConstants.AUTO_DEVICE_APP_TYPE_NATIVE_TEXT);
		} else if (DeviceConstants.AUTO_DEVICE_APP_TYPE_HYBRID.equals(appType)) {
			appTypeValuePair.setValue(DeviceConstants.AUTO_DEVICE_APP_TYPE_HYBRID_TEXT);
		} else if (DeviceConstants.AUTO_DEVICE_APP_TYPE_WEB.equals(appType)) {
			appTypeValuePair.setValue(DeviceConstants.AUTO_DEVICE_APP_TYPE_WEB_TEXT);
		} else if (DeviceConstants.AUTO_DEVICE_APP_TYPE_WECHAT.equals(appType)) {
			appTypeValuePair.setValue(DeviceConstants.AUTO_DEVICE_APP_TYPE_WECHAT_TEXT);
		}

		// 组装device_id
		NameValuePair deviceId = new NameValuePair();
		// 如果类型为模拟器，则不需要device_id
		if (!DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_EMULATOR.equals(deviceType)) {

			deviceId = new NameValuePair(DeviceConstants.JOB_PARAMETER_DEVICE_ID, jobParameter.getDeviceId());
		}
		if (DeviceConstants.AUTO_DEVICE_TYPE_FOR_TEST_IOS_EMULATOR.equals(deviceType)) {
			deviceId = new NameValuePair(DeviceConstants.JOB_PARAMETER_DEVICE_ID, jobParameter.getDeviceId());
		}

		// 组装setting
		NameValuePair setting = new NameValuePair();
		// 如果类型为模拟器，需要加入API和screen
		if (DeviceConstants.AUTO_DEVICE_TYPE_ANDROID_EMULATOR.equals(deviceType)) {
			String androidEmulator = jobParameter.getAndroidEmulator();
			setting = new NameValuePair(DeviceConstants.JOB_PARAMETER_SETTING,
					"{" + androidEmulator + "\"NoReinstall\":true}");
		} else {
			setting = new NameValuePair(DeviceConstants.JOB_PARAMETER_SETTING, "{\"NoReinstall\":true}");
		}

		// 组装job_status_url
		NameValuePair jobStatusUrl = new NameValuePair(DeviceConstants.JOB_STATUS_URL, jobParameter.getJobStatusUrl());
		
		// 组装play
		NameValuePair play = new NameValuePair(DeviceConstants.JOB_PARAMETER_PLAY, jobParameter.getPlay());
		HttpClient httpClient = new HttpClient();
		PostMethod method = new PostMethod(url.toString());

		NameValuePair[] paramPairs = { scriptUrl, appUrl, resultUrl, appTypeValuePair, deviceId, setting,
				jobStatusUrl, play };

		method.setRequestBody(paramPairs);
		httpClient.executeMethod(method);
		String jobid = method.getResponseBodyAsString();
		jobid = jobid.substring(9, jobid.lastIndexOf("\"")).trim();
		return jobid;
	}
    
    
}
